// pages/signin/index.js
const moment = require('moment')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userinfo: {},
        weekList: [],
        nowDaySignin: false,
        baseURl: wx.api.host
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        try {
            const userinfo = wx.getStorageSync('uinfo')
            console.log(userinfo);
            this.setData({
                userinfo
            })
        } catch (error) {
            console.error(error);
        }
        this.getUsersigninfo()
    },
    /**
     * 用户签到操作
     */
    onUsersignin() {
        wx.http.post(wx.api.usersignin).then(res => {
            if (res.code == 1) {
                this.getUserAllInfo()
                this.getUsersigninfo()
            }
        })
    },
    /**
     * 获取用户签到信息
     */
    getUsersigninfo() {
        let {
            nowDaySignin
        } = this.data
        wx.http.get(wx.api.usersigninfo).then(res => {
            const {
                nowdate,
                signinfo
            } = res.data
            let weekList = this.getWeek().map(item => {
                item.expire = moment(nowdate).isAfter(item.date, 'day');
                item.signin = signinfo.some(t => moment(t.date).isSame(item.date, 'day'))
                if (moment(nowdate).isSame(item.date, 'day')) {
                    nowDaySignin = item.signin
                }
                return item;
            })
            this.setData({
                nowDaySignin,
                weekList
            })
        })
    },
    /**
     * 获取更新后用户信息
     */
    getUserAllInfo() {
        wx.http.get(wx.api.GetUserAllInfo).then(res => {
            if (res.code == 1) {
                wx.setStorageSync('uinfo', res.data.data)
                this.setData({
                    userinfo: res.data.data
                })
            }
        })
    },
    /**
     * 计算本周
     */
    getWeek() {
        let now = new Date();
        let nowTime = now.getTime();
        let day = now.getDay();
        let oneDayTime = 24 * 60 * 60 * 1000;
        //显示周一
        let MondayTime = nowTime - (day - 1) * oneDayTime;
        let weekList = ['Mon.', 'Tue.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
        for (let index = 0; index < weekList.length; index++) {
            let item = weekList[index]
            weekList[index] = {
                text: item,
                date: MondayTime + index * oneDayTime
            }
        }
        return weekList
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})